package cn.com.fuhuitong.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.utils.ToastUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


abstract class BaseAbstractFragment : Fragment(), View.OnTouchListener {

    private var isFirstLoad = false

    /**
     * 需要绑定的视图ID
     */
    abstract val layoutResId: Int

    private var rootView: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return rootView ?: inflater.inflate(layoutResId, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        EventBus.getDefault().register(this)
        view.setOnTouchListener(this)
        doBeforeInit()
        initView()
    }

    override fun onResume() {
        super.onResume()
        if (!isFirstLoad) {
            initData()
            isFirstLoad = true
        } else {
            onRefreshLoad()
        }
    }

    override fun onStop() {
        super.onStop()
        val imm: InputMethodManager? =
            requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE)
                    as InputMethodManager?
        val view: View? = requireActivity().currentFocus
        if (imm != null) if (imm.isActive && view != null) {
            if (view.windowToken != null) imm.hideSoftInputFromWindow(
                view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        return true
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventMainThread(eventBus: MainBean<*, *>) {

    }


    /**
     * 在初始化视图之前的操作
     */
    open fun doBeforeInit() = Unit

    /**
     * 初始化UI
     */
    open fun initView() = Unit

    /**
     * 初始化数据
     */
    open fun initData() = Unit


    /**
     * 刷新数据
     */
    open fun onRefreshLoad() = Unit

    fun toast(message: String) {
        ToastUtils.showShort(requireContext(), message)
    }
}